package org.example.Server.service.semester;

import lombok.extern.slf4j.Slf4j;
import org.example.Server.mapper.semester.SemesterMapper;
import org.example.Server.model.semester.*;
import org.example.Server.utils.ResultAPI;
import org.example.Server.utils.SemesterCode;
import org.example.Server.utils.Upload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service
public class SemesterService {
    private final int TOPSTU_NUM = 5;
    private final int SEMACTIVE_NUM = 10;
    @Autowired
    SemesterMapper semesterMapper;

    public ResultAPI getSemesterPersonalList(Integer semesterStatus, Integer techId) {
        List<SemesterVO> semesterVOList = semesterMapper.getSemesterPersonalList(techId);
        List<SemesterVO> res = switch (semesterStatus) {
            case 1 -> semesterVOList.stream()
                    .filter(course -> course.getSemester_status().equals("进行中"))
                    .collect(Collectors.toList());
            case 2 -> semesterVOList.stream()
                    .filter(course -> course.getSemester_status().equals("已结束"))
                    .collect(Collectors.toList());
            default -> semesterVOList;
        };
        return ResultAPI.success(res);
    }

    @Transactional
    public ResultAPI addSemester(SemesterDTO semesterDTO, MultipartFile file) {
        //处理文件
        //先上传到本地浏览器吧
//        String filename = file.getOriginalFilename();
//        int index = filename.lastIndexOf(".");
//        String suffix = filename.substring(index);
//        String newname= UUID.randomUUID().toString()+suffix;
//        log.info("新文件名"+newname);
//        try {
//            file.transferTo(new File(UPLOAD_DIR+newname));
//            log.info("已连接服务器");
//            semesterDTO.setCover(NGINX_HTTP.getPaper_content()+newname);
//        } catch (IOException e) {
//            e.printStackTrace();
//            log.info("未连接服务器暂时不能使用，以存在url替代");
//            semesterDTO.setCover(DEFAULT_SEMCOVER.getPaper_content());
//        }
        String cover = Upload.upload(file);
        semesterDTO.setCover(cover);
        semesterDTO.setSemester_code(SemesterCode.creatUUID());

        semesterMapper.addSemester(semesterDTO);
        semesterMapper.addSemTech(semesterDTO.getSem_id(), semesterDTO.getTech_id(), 1);
        return ResultAPI.success();
    }

    public ResultAPI getDivision(Integer semesterId) {
        List<SemDivisonVO> semDivisonVO = semesterMapper.getDivision(semesterId);
        return ResultAPI.success(semDivisonVO);
    }

    @Transactional
    public ResultAPI getSemesterandVisit(Integer semester_id, Integer tech_id) {
        //查询课堂
        SemesterVO semesterVO = semesterMapper.getSemesterById(semester_id, tech_id);
        //增加访客量,这里需要一个消息队列或许（——）
        semesterMapper.updateVisitCnt(semester_id);
        return ResultAPI.success(semesterVO);
    }

    @Transactional
    public ResultAPI CopySem(SemesterDTO semesterDTO) {
        //复制章节

        //复制作业
        //复制考试

        return ResultAPI.success();
    }


    /**
     * 算学生总成绩列表
     *
     * @param semId
     * @return
     */

    public ResultAPI getSemesterData(Integer semId) {
        List<SemData> semDataList = semesterMapper.getSemesterData(semId);
        List<SemActiveness> semActivenessList = getSemActivenesses(semId);
        List<SemTopStu> semTopStus = new ArrayList<>();
        for (int i = 0; i < semDataList.size(); i++) {
            SemData semData = semDataList.get(i);
            SemActiveness semActiveness = semActivenessList.get(i);
            double score = semData.getExamTotalScore() * 0.7 + semActiveness.getWeight_total() * 0.3;
            SemTopStu semTopStu = new SemTopStu();
            semTopStu.setScore(score);
            semTopStu.setUsername(semData.getStudentName());
            semTopStu.setImg_url(semData.getImg_url());
            semTopStus.add(semTopStu);
        }
        // 排序
        semTopStus.sort((o1, o2) -> Double.compare(o2.getScore(), o1.getScore()));
        semDataList.sort((o1, o2) -> Double.compare(o2.getFinalScore(), o1.getFinalScore()));
        List<SemTopStu> topStusRes = new ArrayList<>();
        for (int i = 0; i < TOPSTU_NUM; i++) {
            SemTopStu semTopStu = semTopStus.get(i);
            topStusRes.add(semTopStu);
        }
        SemDataVO semDataVO = new SemDataVO();
        semDataVO.setSemDataList(semDataList);
        semDataVO.setSemTopStuList(topStusRes);
        return ResultAPI.success(semDataVO);
    }

    /**
     * 获取学生课堂列表
     *
     * @param stuId
     * @param semesterStatus
     * @return
     */
    public ResultAPI getSemStuList(int stuId, Integer semesterStatus) {
        List<SemStuVO> semesterVOList = semesterMapper.getSemesterStuList(stuId);
        List<SemStuVO> res = switch (semesterStatus) {
            case 1 -> semesterVOList.stream()
                    .filter(course -> course.getSemester_status().equals("进行中"))
                    .collect(Collectors.toList());
            case 2 -> semesterVOList.stream()
                    .filter(course -> course.getSemester_status().equals("已结束"))
                    .collect(Collectors.toList());
            default -> semesterVOList;
        };
        return ResultAPI.success(res);
    }

    /**
     * 学生加入课堂
     *
     * @param semAddStu
     * @return
     */
    public ResultAPI addSemesterStu(SemAddStu semAddStu) {
        int semId = semesterMapper.getSemIdByCode(semAddStu.getSemester_code());
        semAddStu.setSemester_id(semId);
        SemesterVO semesterVO = semesterMapper.getSemStu(semAddStu);

        if (semesterVO != null) return ResultAPI.error("学生已加入课堂");

        semesterMapper.addSemesterStu(semAddStu);
        return ResultAPI.success();
    }

    /**
     * 获取学生这边的课堂详情
     *
     * @param stuId
     * @param semesterId
     * @return
     */
    public ResultAPI getSemStuDetail(Integer stuId, Integer semesterId) {
        SemesterVO semesterVO = semesterMapper.getSemStuDetail(stuId, semesterId);
        return ResultAPI.success(semesterVO);
    }

    /**
     * 获取学生活跃度
     *
     * @param semId
     * @return
     */
    public ResultAPI getActiveness(Integer semId) {
        List<SemActiveness> semActiveness = getSemActivenesses(semId);
        // 使用 Collections.sort 方法进行排序
        semActiveness.sort((SemActiveness s1, SemActiveness s2) -> {
            // 按照 total 字段从大到小排序
            return Integer.compare(s2.getWeight_total(), s1.getWeight_total());
        });
        List<SemActiveness> res = new ArrayList<>();
        int count = semActiveness.size();
        for (int i = 0; i < (Math.min(count, SEMACTIVE_NUM)); i++) {
            res.add(semActiveness.get(i));
        }
        return ResultAPI.success(res);
    }

    /**
     * 获取每个学生的课堂活跃度
     *
     * @param semId
     * @return
     */
    private List<SemActiveness> getSemActivenesses(Integer semId) {
        List<SemActiveness> semActiveness = semesterMapper.getActiveness(semId);
        for (SemActiveness item : semActiveness) {
            Integer total = item.getStuExam_cnt() * 7 + item.getStuHmk_cnt() * 8 + item.getStuEach_cnt() * 3 + item.getStuRe_cnt() * 5;
            item.setWeight_total(total);
        }
        return semActiveness;
    }

    /**
     * 获取课堂作业得分率
     *
     * @param semId
     * @return
     */
    public ResultAPI getHmkScoreRate(Integer semId) {
        List<SemHmkData> semHmkData = semesterMapper.getHmkScoreRate(semId);
        return ResultAPI.success(semHmkData);
    }

    /**
     * 获取课堂作业评分等级人数
     *
     * @param semId
     * @return
     */
    public ResultAPI getHmkLevel(Integer semId) {
        List<SemHmkLevel> semHmkLevels = semesterMapper.getHmkLevel(semId);
        return ResultAPI.success(semHmkLevels);
    }

    public ResultAPI deleteSem(Integer semId) {
        semesterMapper.deleteSem(semId);
        return ResultAPI.success();
    }

    public ResultAPI updateSem(SemesterDTO semesterDTO) {
        semesterMapper.updateSem(semesterDTO);
        return ResultAPI.success();
    }

    /**
     * 获取学生课堂数据分析
     *
     * @param stuId
     * @param semesterId
     * @return
     */
    public ResultAPI getStuData(Integer stuId, Integer semesterId) {
        SemStuData semStuData = new SemStuData();
        List<SemStuHmkData> semStuHmkDatas = semesterMapper.getStuHmkData(stuId, semesterId);
        List<SemStuExamData> semStuExamDatas = semesterMapper.getStuExamData(stuId, semesterId);

        semStuData.setSemStuHmkDatas(semStuHmkDatas);
        semStuData.setSemStuExamDatas(semStuExamDatas);

        return ResultAPI.success(semStuData);
    }

    /**
     * 获取课堂学生分班列表
     *
     * @param semId
     * @param division_id
     * @return
     */

    public ResultAPI getSemStuDivList(Integer semId, Integer division_id) {
        List<SemStuDivsion> list = semesterMapper.getSemStuDivList(semId, division_id);
        return ResultAPI.success(list);
    }

    /**
     * 课堂学生调班
     *
     * @param semStuDivsion
     * @return
     */
    public ResultAPI updateStuDivision(SemStuDivsion semStuDivsion) {
        semesterMapper.updateStuDivision(semStuDivsion);
        return ResultAPI.success();
    }

    /**
     * 删除分班
     *
     * @param divisionId
     * @return
     */
    @Transactional
    public ResultAPI deleteDivision(Integer divisionId) {
        semesterMapper.updateDelDiv(divisionId);
        semesterMapper.deleteDivision(divisionId);
        return ResultAPI.success();
    }

    /**
     * 学生退课
     *
     * @param stuSemesterId
     * @return
     */
    public ResultAPI deleteStuSem(Integer stuSemesterId) {
        semesterMapper.deleteStuSem(stuSemesterId);
        return ResultAPI.success();
    }


    public ResultAPI addDivision(SemDivisonDTO semDivisonDTO) {
        semesterMapper.addDivision(semDivisonDTO);
        return ResultAPI.success(semDivisonDTO);
    }
}
